'use strict';

exports.main = async (event, context) => {
  console.log('创建聊天消息云函数被调用，参数:', event)
  
  const { 
    taskId, 
    messageType = 'system', 
    senderId = 'admin', 
    receiverId, 
    content, 
    title,
    senderInfo = {},
    receiverInfo = {},
    extraData = {}
  } = event
  
  // 参数验证
  if (!taskId || !receiverId || !content) {
    return { 
      code: 400, 
      msg: '参数不完整，需要 taskId, receiverId, content' 
    }
  }

  const db = uniCloud.database()
  
  try {
    // 构建符合 chatMessages.schema.json 的消息记录
    const chatMessage = {
      taskId: taskId, // 关联的任务ID
      type: messageType, // 消息类型：system, text, image, card
      senderId: senderId, // 发送者用户ID
      senderAvatar: senderInfo.avatar || '', // 发送者头像
      senderNickname: senderInfo.nickname || '系统管理员', // 发送者昵称
      receiverId: receiverId, // 接收者用户ID
      receiverAvatar: receiverInfo.avatar || '', // 接收者头像
      receiverNickname: receiverInfo.nickname || '', // 接收者昵称
      content: content, // 消息内容
      createTime: new Date(), // 创建时间
      status: 'sent', // 消息状态
      title: title || '' // 消息标题（可选）
    }
    
    // 如果接收者信息不完整，尝试从数据库获取
    if (!receiverInfo.nickname || !receiverInfo.avatar) {
      try {
        const userResult = await db.collection('uni-id-users')
          .where({ _id: receiverId })
          .field({ nickname: true, avatar: true })
          .get()
        
        if (userResult.data && userResult.data.length > 0) {
          const user = userResult.data[0]
          if (!receiverInfo.nickname) {
            chatMessage.receiverNickname = user.nickname || '用户'
          }
          if (!receiverInfo.avatar) {
            chatMessage.receiverAvatar = user.avatar || ''
          }
        } else {
          chatMessage.receiverNickname = '用户'
        }
      } catch (userError) {
        console.log('获取用户信息失败，使用默认值:', userError)
        chatMessage.receiverNickname = '用户'
      }
    }
    
    // 如果是系统消息且发送者信息不完整，补充系统管理员信息
    if (messageType === 'system' && senderId === 'admin') {
      if (!senderInfo.nickname) {
        chatMessage.senderNickname = '系统管理员'
      }
      if (!senderInfo.avatar) {
        chatMessage.senderAvatar = '' // 可以设置系统头像URL
      }
    }
    
    // 添加额外的字段（如果有）
    if (extraData.imageUrl) {
      chatMessage.imageUrl = extraData.imageUrl
    }
    if (extraData.location) {
      chatMessage.location = extraData.location
    }
    
    // 保存到 chatMessages 表
    const result = await db.collection('chatMessages').add(chatMessage)
    
    console.log('聊天消息已保存:', result.id)
    
    return {
      code: 200,
      msg: '聊天消息创建成功',
      data: {
        messageId: result.id,
        chatMessage: chatMessage
      }
    }
    
  } catch (error) {
    console.error('创建聊天消息失败:', error)
    return {
      code: 500,
      msg: '创建聊天消息失败: ' + error.message,
      data: null
    }
  }
}
